using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Xml;
using System.Text.RegularExpressions;
using umbraco.presentation;
using umbraco.cms.businesslogic.web;

namespace umbraco {
    /// <summary>
    /// Summary description for WebForm1.
    /// </summary>
    /// 
    public partial class UmbracoDefault : Page {

        private Guid m_version = Guid.Empty;
        private string m_tmp = requestHandler.cleanUrl();
        private page m_umbPage = null;
        private requestHandler m_umbRequest = null;

        private bool m_validateRequest = true;

        /// <summary>
        /// To turn off request validation set this to false before the PageLoad event. This equelevant to the validateRequest page directive
        /// and has nothing to do with "normal" validation controls. Default value is true.
        /// </summary>
        public bool ValidateRequest
        {
            get { return m_validateRequest; }
            set { m_validateRequest = value; }
        }

        protected override void Render(HtmlTextWriter output) {

            // Get content
            TextWriter tempWriter = new StringWriter();
            base.Render(new HtmlTextWriter(tempWriter));
            string pageContents = tempWriter.ToString();

            pageContents = template.ParseInternalLinks(pageContents);

            // Parse javascript without types
            // NH 15.07.08 - Why should we do that on every page when people should fix their templates instead.
//            pageContents =
//                pageContents.Replace("<script language=\"javascript\">", "<script language=\"javascript\" type=\"text/javascript\">");

            output.Write(pageContents);
            //// Parse form name
            //if (HttpContext.Current.Items["VirtualUrl"] != null) {
            //    Regex formReplace = new Regex("action=\"default.aspx([^\"]*)\"");
            //    if (formReplace.ToString() != "")
            //        output.Write(
            //            formReplace.Replace(pageContents, "action=\"" + Convert.ToString(HttpContext.Current.Items["VirtualUrl"]) + "\""));
            //} else
            //    base.Render(output);
        }

        void Page_PreInit(Object sender, EventArgs e) {
            Trace.Write("umbracoInit", "handling request");

            bool editMode = UmbracoContext.Current.LiveEditingContext.Enabled;

            if (editMode)
                ValidateRequest = false;

            if (m_tmp != "") {
                // Check numeric
                string tryIntParse = m_tmp.Replace("/", "").Replace(".aspx", string.Empty);
                int result;
                if (int.TryParse(tryIntParse, out result)) {
                    m_tmp = m_tmp.Replace(".aspx", string.Empty);

                    // Check for request
                    if (!string.IsNullOrEmpty(Request["umbVersion"])) {
                        // Security check
                        BasePages.UmbracoEnsuredPage bp = new BasePages.UmbracoEnsuredPage();
                        bp.ensureContext();
                        m_version = new Guid(Request["umbVersion"]);
                    }
                }
            }


            if (m_version != Guid.Empty) {
                HttpContext.Current.Items["pageID"] = m_tmp.Replace("/", "");
                m_umbPage = new page(int.Parse(m_tmp.Replace("/", "")), m_version);
            } else {
                m_umbRequest = new requestHandler(content.Instance.XmlContent, m_tmp);
                Trace.Write("umbracoInit", "Done handling request");
                if (m_umbRequest.currentPage != null) {
                    HttpContext.Current.Items["pageID"] = m_umbRequest.currentPage.Attributes.GetNamedItem("id").Value;

                    // Handle edit
                    if (editMode)
                    {
                        Document d = new Document(int.Parse(m_umbRequest.currentPage.Attributes.GetNamedItem("id").Value));
                        m_umbPage = new page(d.Id, d.Version);
                    } else
                        m_umbPage = new page(m_umbRequest.currentPage);
                }
            }

            if (UmbracoSettings.UseAspNetMasterPages) {
                if (m_umbPage != null)
                    this.MasterPageFile = template.GetMasterPageName(m_umbPage.Template);
                
                initUmbracoPage();
            }
        }

        public Control pageContent = new Control();

        protected void Page_Load(object sender, EventArgs e) {

            if (ValidateRequest)
                Request.ValidateInput();

            if (!String.IsNullOrEmpty(Request["umbDebugShowTrace"])) {
                if (!GlobalSettings.DebugMode) {
                    Page.Trace.IsEnabled = false;
                }
            } else
                Page.Trace.IsEnabled = false;

            // test for edit mode
            /*if (helper.UserInLiveEditingMode())
            {
                // turn off request validation when in Live Editing mode
                // can probably be removed
                new System.Web.Configuration.PagesSection().ValidateRequest = false;
                if (ScriptManager.GetCurrent(this.Page) == null)
                {
                    throw new Exception("Umbraco Live Editing Requires a Script Manager in the template");
                }
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "umbEditCss", "<link href=\"" + GlobalSettings.Path + "/css/umbLiveEditing.css\" type=\"text/css\" rel=\"stylesheet\"></link>", false);
                Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "umbEditJs", GlobalSettings.Path + "/js/umbLiveEditing.js");
                Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "umbEditPrototype", GlobalSettings.Path + "/js/prototype.js");
            }*/

        }


        #region Web Form Designer generated code

        protected override void OnInit(EventArgs e) {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();

            if (!UmbracoSettings.UseAspNetMasterPages)
                initUmbracoPage();
            base.OnInit(e);
        }

        private void initUmbracoPage() {
            if (!UmbracoSettings.EnableSplashWhileLoading || !content.Instance.isInitializing) {

                // Add a content placeholder


                // TODO: Find 404 error
                if (m_umbPage != null) {
                    // Add page elements to global items
                    System.Web.HttpContext.Current.Items.Add("pageElements", m_umbPage.Elements);
                    string tempCulture = m_umbPage.GetCulture();
                    if (tempCulture != "") {
                        System.Web.HttpContext.Current.Trace.Write("default.aspx", "Culture changed to " + tempCulture);
                        System.Threading.Thread.CurrentThread.CurrentCulture =
                            System.Globalization.CultureInfo.CreateSpecificCulture(tempCulture);
                        System.Threading.Thread.CurrentThread.CurrentUICulture = System.Threading.Thread.CurrentThread.CurrentCulture;
                    }

                    if (!UmbracoSettings.UseAspNetMasterPages) {
                        layoutControls.umbracoPageHolder pageHolder = new umbraco.layoutControls.umbracoPageHolder();
                        pageHolder.ID = "umbPageHolder";
                        Page.Controls.Add(pageHolder);
                        m_umbPage.RenderPage(m_umbPage.Template);
                        layoutControls.umbracoPageHolder umbPageHolder =
                            (layoutControls.umbracoPageHolder)Page.FindControl("umbPageHolder");
                        umbPageHolder.Populate(m_umbPage);
                    }

                    // Stat
                    if (GlobalSettings.EnableStat)
                        if (Session["umbracoSessionId"] != null) {
                            // If session just has been initialized we should use the cookie from the response object
                            if (Session["umbracoSessionId"] == null)
                                cms.businesslogic.stat.Session.AddEntry(new Guid(Session["umbracoSessionId"].ToString()), m_umbPage.PageID);
                            else
                                cms.businesslogic.stat.Session.AddEntry(new Guid(Session["umbracoSessionId"].ToString()), m_umbPage.PageID);
                        }
                } else {
                    // If there's no published content, show friendly error
                    if (umbraco.content.Instance.XmlContent.SelectSingleNode("/root/node") == null)
                        Response.Redirect("config/splashes/noNodes.aspx");
                    else {

                        Response.StatusCode = 404;
                        Response.Write("<html><body><h1>Page not found</h1>");
                        if (m_umbRequest != null)
                            HttpContext.Current.Response.Write("<h3>No umbraco document matches the url '" + HttpUtility.HtmlEncode(Request.Url.ToString()) + "'</h3><p>umbraco tried this to match it using this xpath query'" + m_umbRequest.PageXPathQuery + "')");
                        else
                            HttpContext.Current.Response.Write("<h3>No umbraco document matches the url '" + HttpUtility.HtmlEncode(Request.Url.ToString()) + "'</h3>");
                        Response.Write("</p>");
                        Response.Write("<p>This page can be replaced with a custom 404 page by adding the id of the umbraco document to show as 404 page in the /config/umbracoSettings.config file. Just add the id to the '/settings/content/errors/error404' element.</p>");
                        Response.Write("<p>For more information, visit <a href=\"http://umbraco.org/redir/custom-404\">information about custom 404</a> on the umbraco website.</p>");
                        Response.Write("<p style=\"border-top: 1px solid #ccc; padding-top: 10px\"><small>This page is intentionally left ugly ;-)</small></p>");
                        Response.Write("</body></html>");
                    }
                }
            } else {
                Response.Redirect("config/splashes/booting.aspx?orgUrl=" + Request.Url);
            }
        }

        /// <summary>
        /// Required method for Designer support - do not modify
        /// the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent() {
        }

        #endregion
    }
}
